/**
 * 调用摄像头以及图片上传
 */
var TakePhoto = {

	//点击拍照按钮或者图片区域
	MakePhoto: function(parameter) {
		if (mui.os.plus) {
			var a = [{
				title: "拍照",
				type: "make"
			}, {
				title: "从手机相册选择",
				type: "Choose"
			}];
			if (parameter.Title != undefined && parameter.Title == "照片") {
				var deletePhoto = new Object();
				deletePhoto.title = "删除照片";
				a.push(deletePhoto);
			}
			plus.nativeUI.actionSheet({
				title: parameter.Title == undefined ? '修改用户头像' : parameter.Title,
				cancel: "取消",
				buttons: a
			}, function(b) {
				/*actionSheet 按钮点击事件*/
				switch (b.index) {
					case 0:
						break;
					case 1:
						TakePhoto.GetImage(parameter); /*拍照*/
						break;
					case 2:
						TakePhoto.GalleryImg(parameter); /*打开相册*/
						break;
					case 3:
						TakePhoto.DeleteImage(parameter);
					default:
						break;
				}
			})
		}
	},

	/*删除照片*/
	DeleteImage: function(parameter) {
		parameter.Success("DeleteImage");
	},

	/*拍照*/
	GetImage: function(parameter) {
		var fileName = new Date().getTime();
		var c = plus.camera.getCamera();
		c.supportedImageFormats = "1024*768";
		c.captureImage(function(e) {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				var s = entry.toLocalURL() + "?version=" + new Date().getTime();
				TakePhoto.CompressImage(s);
				TakePhoto.SavePicture(s);
				parameter.Success(s);
			}, function(e) {
				mui.alert("读取拍照文件错误：" + e.message);
			});
		}, function(s) {
			//mui.alert("error：" + s); 
			console.log("error" + s);
		}, {
			//设置文件名称和路径
			filename: "_doc/" + fileName + ".png",
			//设置分辨率
			supportedImageFormats: "640*480"
		})
	},

	//保存到手机相册
	SavePicture: function(path) {
		plus.gallery.save(path, function() {
			mui.toast("图片已经保存到相册");
		});
	},

	//图片压缩
	CompressImage: function(filePath) {
		plus.zip.compressImage({
				src: filePath,
				dst: filePath,
				quality: 50,
				overwrite: true
			},
			function() {
				//alert("Compress success!");
			},
			function(error) {
				//alert("Compress error!");
			});
	},

	//本地相册选择 
	GalleryImg: function(parameter) {
		var fileName = new Date().getTime() + ".png";
		plus.gallery.pick(function(a) {
			plus.io.resolveLocalFileSystemURL(a, function(entry) {
				var e = entry.fullPath +
				          "?version=" + new Date()
				          .getTime();
				      parameter.Success(e);
				// plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
				// 	root.getFile(fileName, {}, function(file) {
				// 		var e = file.fullPath +
				// 		          "?version=" + new Date()
				// 		          .getTime();
				// 		      parameter.Success(e);
							  
				// 		//文件已存在 
				// 		// file.remove(function() {
				// 		// 	console.log("file remove success");
				// 		// 	entry.copyTo(root, fileName, function(e) {
				// 		// 			var e = e.fullPath +
				// 		// 				"?version=" + new Date()
				// 		// 				.getTime();
				// 		// 			parameter.Success(e);
				// 		// 			//变更大图预览的src 
				// 		// 			//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现 
				// 		// 		},
				// 		// 		function(e) {
				// 		// 			mui.alert("copy image fail:" + e
				// 		// 				.message);
				// 		// 			console.log('copy image fail:' +
				// 		// 				e.message);
				// 		// 		});
				// 		}, function() {
				// 			mui.alert("delete image fail:" + e.message);
				// 			console.log("delete image fail:" + e
				// 				.message);
				// 		});
				// 	}, function() {
				// 		//文件不存在 
				// 		// entry.copyTo(root, fileName, function(e) {
				// 		// 		var path = e.fullPath + "?version=" +
				// 		// 			new Date().getTime();
				// 		// 		parameter.Success(path);
				// 		// 	},
				// 		// 	function(e) {
				// 		// 		mui.alert("copy image fail:" + e.message);
				// 		// 		console.log('copy image fail:' + e.message);
				// 		// 	});
				// 	});
				// }, function(e) {
				// 	mui.alert("get _www folder fail");
				// 	console.log("get _www folder fail");
				// })
			}, function(e) {
				mui.alert("读取拍照文件错误：" + e.message);
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(a) {}, {
			filter: "image"
		})
	},

	//上传图片 
	UploadImage: function(parameter) {
		var image = new Image();
		image.src = parameter.imgPath;
		var wt = plus.nativeUI.showWaiting("图片上传中");
		var token = localStorage.getItem('token');
		
		var headers = {
			'Content-Type': 'application/json'
		};		
		
		var token = localStorage.getItem("token");
		if (token) {
			headers['authorization'] = token;
		}
		
		var task = plus.uploader.createUpload(parameter.url, {
				method: "POST",
				headers: headers
			},
			function(t, status) { //上传完成
				wt.close(); //关闭等待提示按钮
				if (status == 200) {
					//alert("上传成功："+t.responseText);
					parameter.Success(t.responseText);					
				} else {
					mui.alert("上传失败：" + status);
				}
			}
		);
		//添加其他参数
		//task.addData("UploadPath", "AppPicture");
		task.addFile(image.src, {
			key: "file"
		});
		task.start();
	},

	//将图片压缩转成base64 
	GetBase64Image: function(img) {
		var canvas = document.createElement("canvas");
		var width = img.width;
		var height = img.height;
		// calculate the width and height, constraining the proportions 
		if (width > height) {
			if (width > 100) {
				height = Math.round(height *= 100 / width);
				width = 100;
			}
		} else {
			if (height > 100) {
				width = Math.round(width *= 100 / height);
				height = 100;
			}
		}
		canvas.width = width; /*设置新的图片的宽度*/
		canvas.height = height; /*设置新的图片的长度*/
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, width, height); /*绘图*/
		var dataURL = canvas.toDataURL("image/png", 0.8);
		return dataURL.replace("data:image/png;base64,", "");
	},
}